<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>数组降维 | S.E.</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="将多维数组（尤其是二维数组）转化为一维数组是业务开发中的常用逻辑，除了使用朴素的循环转换以外，我们还可以利用Javascript的语言特性实现更为简洁优雅的转换。本文将从朴素的循环转换开始，逐一介绍三种常用的转换方法，并借此简单回顾Array.prototype.concat方法和Function.prototype.apply方法。 以下代码将以把二维数组降维到一维数组为例。 1. 朴素的转换1">
<meta property="og:type" content="article">
<meta property="og:title" content="数组降维">
<meta property="og:url" content="http://seveneyes.top/2017/11/03/数组降维/index.html">
<meta property="og:site_name" content="S.E.">
<meta property="og:description" content="将多维数组（尤其是二维数组）转化为一维数组是业务开发中的常用逻辑，除了使用朴素的循环转换以外，我们还可以利用Javascript的语言特性实现更为简洁优雅的转换。本文将从朴素的循环转换开始，逐一介绍三种常用的转换方法，并借此简单回顾Array.prototype.concat方法和Function.prototype.apply方法。 以下代码将以把二维数组降维到一维数组为例。 1. 朴素的转换1">
<meta property="og:updated_time" content="2017-11-03T03:41:32.478Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数组降维">
<meta name="twitter:description" content="将多维数组（尤其是二维数组）转化为一维数组是业务开发中的常用逻辑，除了使用朴素的循环转换以外，我们还可以利用Javascript的语言特性实现更为简洁优雅的转换。本文将从朴素的循环转换开始，逐一介绍三种常用的转换方法，并借此简单回顾Array.prototype.concat方法和Function.prototype.apply方法。 以下代码将以把二维数组降维到一维数组为例。 1. 朴素的转换1">
  
    <link rel="alternate" href="/atom.xml" title="S.E." type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  

</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">S.E.</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">成功的人抄袭，伟大的人剽窃</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://seveneyes.top"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-数组降维" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2017/11/03/数组降维/" class="article-date">
  <time datetime="2017-11-03T01:30:14.294Z" itemprop="datePublished">2017-11-03</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      数组降维
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>将多维数组（尤其是二维数组）转化为一维数组是业务开发中的常用逻辑，除了使用朴素的循环转换以外，我们还可以利用Javascript的语言特性实现更为简洁优雅的转换。本文将从朴素的循环转换开始，逐一介绍三种常用的转换方法，并借此简单回顾Array.prototype.concat方法和Function.prototype.apply方法。</p>
<p>以下代码将以把二维数组降维到一维数组为例。</p>
<h2 id="1-朴素的转换"><a href="#1-朴素的转换" class="headerlink" title="1. 朴素的转换"></a>1. 朴素的转换</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">reduceDimension</span>(<span class="params">arr</span>) </span>&#123;    </div><div class="line">  <span class="keyword">var</span> reduced = [];    </div><div class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;    </div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> j = <span class="number">0</span>; j &lt; arr[i].length; j++) &#123;            					</div><div class="line">          reduced.push(arr[i][j]);   </div><div class="line">        &#125;   </div><div class="line">    &#125;   </div><div class="line">  <span class="keyword">return</span> reduced;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>此方法思路简单，利用双重循环遍历二维数组中的每个元素并放到新数组中。</p>
<h2 id="2-利用concat转换"><a href="#2-利用concat转换" class="headerlink" title="2. 利用concat转换"></a>2. 利用concat转换</h2><p>先来回顾一下MDN上对于该方法的介绍：</p>
<p>“concat creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).”<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" target="_blank" rel="external">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat</a></p>
<p>即如果concat方法的参数是一个元素，该元素会被直接插入到新数组中；如果参数是一个数组，该数组的各个元素将被插入到新数组中；将该特性应用到代码中：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">reduceDimension</span>(<span class="params">arr</span>) </span>&#123;</div><div class="line">  <span class="keyword">var</span> reduced = [];</div><div class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arr.length; i++)&#123;</div><div class="line">    reduced = reduced.concat(arr[i]);</div><div class="line">  &#125;    </div><div class="line">  <span class="keyword">return</span> reduced;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><strong>在MDN上看到的用reduce 和concat</strong><br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">let</span> a =   [[<span class="number">0</span>, <span class="number">1</span>], [<span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>]].reduce(<span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>) </span>&#123;</div><div class="line">  <span class="keyword">return</span> a.concat(b);</div><div class="line">&#125;, []);<span class="comment">//a = [0,1,2,3,4,5]</span></div></pre></td></tr></table></figure></p>
<p>arr的每一个元素都是一个数组，作为concat方法的参数，数组中的每一个子元素又都会被独立插入进新数组。<br>利用concat方法，我们将双重循环简化为了单重循环。</p>
<ol>
<li>利用apply和concat转换<br>按照惯例，先来回顾一下MDN上对于apply方法的介绍：</li>
</ol>
<p>“The apply() method calls a function with a given this value and arguments provided as an array.”</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" target="_blank" rel="external">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply</a></p>
<p>即apply方法会调用一个函数，apply方法的第一个参数会作为被调用函数的this值，apply方法的第二个参数（一个数组，或类数组的对象）会作为被调用对象的arguments值，也就是说该数组的各个元素将会依次成为被调用函数的各个参数；将该特性应用到代码中：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">reduceDimension</span>(<span class="params">arr</span>) </span>&#123;</div><div class="line"><span class="keyword">return</span> <span class="built_in">Array</span>.prototype.concat.apply([], arr);</div><div class="line">&#125;</div><div class="line"><span class="string">``</span><span class="string">`   </span></div><div class="line"><span class="string"></span></div><div class="line"><span class="string">arr作为apply方法的第二个参数，本身是一个数组，数组中的每一个元素（还是数组，即二维数组的第二维）会被作为参数依次传入到concat中，效果等同于[].concat([1,2], [3,4], [5,6])。</span></div><div class="line"><span class="string">利用apply方法，我们将单重循环优化为了一行代码，很简洁有型有木有啊</span></div><div class="line"><span class="string">读者也可参照本文思路，自己利用递归实现N维数组降维的逻辑。(instanceof的用法后续再说)</span></div><div class="line"><span class="string"></span></div><div class="line"><span class="string">`</span><span class="string">``</span>js</div><div class="line"><span class="keyword">var</span> arrs = [<span class="number">1</span>, [<span class="number">23</span>, <span class="number">32</span>], <span class="number">42</span>, [<span class="number">0</span>, <span class="number">33</span>, [<span class="number">55</span>, <span class="number">39</span>, [<span class="number">10</span>, <span class="number">331</span>, [<span class="number">15</span>, <span class="number">34</span>]]]]];</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">jiangwei1</span>(<span class="params">arrs</span>) </span>&#123;</div><div class="line">  <span class="keyword">var</span> newarrs = [];</div><div class="line">  <span class="function"><span class="keyword">function</span> <span class="title">digui</span>(<span class="params">arrs</span>) </span>&#123;</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arrs.length; i++) &#123;</div><div class="line">      <span class="keyword">if</span> (arrs[i] <span class="keyword">instanceof</span> <span class="built_in">Array</span>) &#123;</div><div class="line">        digui(arrs[i]);</div><div class="line">      &#125; <span class="keyword">else</span> &#123;</div><div class="line">        newarrs.push(arrs[i]);</div><div class="line">    &#125;</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  digui(arrs);</div><div class="line">  <span class="keyword">return</span> newarrs</div><div class="line">&#125;</div><div class="line">jiangwei1(arrs);<span class="comment">//[1, 23, 32, 42, 0, 33, 55, 39, 10, 331, 15, 34]</span></div></pre></td></tr></table></figure></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://seveneyes.top/2017/11/03/数组降维/" data-id="cjf9vxkwl0006f4qscg0tiat0" class="article-share-link">Share</a>
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/11/03/常见的排序方法/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          常见的排序方法
        
      </div>
    </a>
  
  
    <a href="/2017/11/03/函数在其他文件里面调用/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">函数在其他文件里面调用</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">November 2017</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2018/03/27/入门教程/">入门教程</a>
          </li>
        
          <li>
            <a href="/2017/11/21/jasmine测试框架的使用/">jasmine测试框架的使用</a>
          </li>
        
          <li>
            <a href="/2017/11/03/用码云挂载页面/">用码云挂载页面</a>
          </li>
        
          <li>
            <a href="/2017/11/03/js高阶函数/">map,filter.reduce的区别</a>
          </li>
        
          <li>
            <a href="/2017/11/03/js的number的数据处理/">js的number的数据处理（取位）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 SevenEyes<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>

  </div>
</body>
</html>